package com.occludens.admin.datamodel;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Load;
import com.googlecode.objectify.annotation.Subclass;

@Subclass(index=true)
@Cache
public class Policy extends AdminObjectDataModel {
	@Index private String sequence;
	@Load private List<Ref<Type>> governedTypes = new ArrayList<Ref<Type>>();
	@Load private List<Ref<State>> states = new ArrayList<Ref<State>>();
	
	protected Policy() {} // Mandatory for Objectify
	
	public Policy(String name) {
		super(name);
	}
	
	public List<Type> getGovernedTypes() {
		List<Type> returnList = new ArrayList<Type>();
		Iterator<Ref<Type>> governedTypesItr = this.governedTypes.iterator();
		while (governedTypesItr.hasNext()) {
			returnList.add(governedTypesItr.next().get());
		}//End of while governedTypesItr
		return returnList;
	}

	public void setGovernedTypes(List<Type> types) {
		Iterator<Type> typesItr = types.iterator();
		while (typesItr.hasNext()) {
			Ref<Type> typeRef = Ref.create(typesItr.next());
			if (!this.governedTypes.contains(typeRef)) {
				this.governedTypes.add(typeRef);
			}
		}//End of while typesItr
	}

	public void addGovernedTypes(Type... types) {
		for (int i=0; i<types.length; i++) {
			Ref<Type> typeRef = Ref.create(types[i]);
			if (!this.governedTypes.contains(typeRef)) {
				this.governedTypes.add(typeRef);
			}
		}
	}

	public void removeGovernedTypes(Type... types) {
		for (int i=0; i<types.length; i++) {
			Ref<Type> typeRef = Ref.create(types[i]);
			if (this.governedTypes.contains(typeRef)) {
				this.governedTypes.remove(typeRef);
			}
		}
	}
	
	public List<State> getStates() {
		List<State> returnList = new ArrayList<State>();
		Iterator<Ref<State>> statesItr = this.states.iterator();
		while (statesItr.hasNext()) {
			returnList.add(statesItr.next().get());
		}//End of while statesItr
		return returnList;
	}

	public void setStates(List<State> states) {
		Iterator<State> statesItr = states.iterator();
		while (statesItr.hasNext()) {
			Ref<State> stateRef = Ref.create(statesItr.next());
			if (!this.states.contains(stateRef)) {
				this.states.add(stateRef);
			}
		}//End of while statesItr
	}

	public void addStates(State... states) {
		for (int i=0; i<states.length; i++) {
			Ref<State> typeRef = Ref.create(states[i]);
			if (!this.states.contains(typeRef)) {
				this.states.add(typeRef);
			}
		}
	}

	public void removeStates(State... states) {
		for (int i=0; i<states.length; i++) {
			Ref<State> typeRef = Ref.create(states[i]);
			if (this.states.contains(typeRef)) {
				this.states.remove(typeRef);
			}
		}
	}
}
